package com.whfp.coky.ui.base.vm

import android.bluetooth.BluetoothDevice
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.seuic.sleduhf.DecodeInfo
import com.seuic.sleduhf.EPC
import com.seuic.sleduhf.UhfCallback
import com.whfp.coky.R
import com.whfp.coky.databinding.ActivityRfidBinding
import com.whfp.coky.other.Constants
import com.whfp.coky.ui.base.BaseActivity
import com.whfp.coky.ui.base.BaseViewModel
import com.whfp.coky.ui.base.RFIDAct
import com.whfp.coky.ui.task.act.ScanCodeAct
import com.whfp.coky.utils.LogUtil
import com.whfp.coky.utils.RFIDTool
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *
 *
 * created by coky on 2022/3/1
 */
abstract class RFIDVM : BaseViewModel<ActivityRfidBinding>() {

    //RFID操作工具类
    val myRFID: RFIDTool = RFIDTool.getInstance()
    val mUhfCallback: UhfCallback by lazy { getUhfCallback() }
    lateinit var mac: String//设备mac

    //当前是否处理寻到的码
    var isEnable = false
    //寻到的卡的集合
    var data: MutableSet<EpcBean> = mutableSetOf<EpcBean>()
    //当前信号最强的标签
    var currentRssiMax: EpcBean? = null
    //当前标签的内容
    var content = ""

// LD数据
    var toConnLD = MutableLiveData(false)//开启/断开连接
    var connStatusLD = MutableLiveData<Int>()//练级状态
    var scanModeLD = MutableLiveData<Int>()//扫描类型

    fun autoConn() {//设备会自动连接
        if (RFIDTool.mDevice !== null &&
            RFIDTool.mDevice.sledAddress !== null &&
            !RFIDTool.mDevice.sledAddress.equals("null")
        ) {//设备已连接
//           isConn.value = true
        }
    }


    override fun observe(activity: BaseActivity<*, *>, owner: LifecycleOwner) {
        super.observe(activity, owner)
        toConnLD.observe(owner, Observer {
            if (it) {
//                启动连接流程
                ScanCodeAct.start(activity,Constants.DEV_TYPE_RFID,null)//需要携带意图
            } else {
//                开启断开操作
                myRFID.disconnect()
            }
        })

        connStatusLD.observe(owner, Observer {
            activity.hideDialog()
            when (it) {
                0 -> viewConned(activity)
                -1-> viewDisConn(activity)
                else -> viewTimeOut(activity)
            }

        })
        connStatusLD.observe(owner, Observer {
            activity.hideDialog()
            when (it) {
                0 -> {
                    if (data.isEmpty()) {
                        activity.toast("本次未寻到卡！")
                    } else {
                        /**
                         * 停止寻卡后根据数据 更新后续操作
                         */
                        currentRssiMax = data.stream().max(Comparator.comparingInt(EpcBean::rssi)).get()
                        LogUtil.e("信号最强的是：${currentRssiMax?.getId()},信号强度是：${currentRssiMax?.rssi}")
                        (activity as RFIDAct<*>).loadView()
                        doUpdate(activity)//读卡，生成二维码，写卡http请求获取二维码
                    }
                }//停止寻卡
                1 -> data.clear()//开始寻卡
            }

        })
        checkedDevLD.observe(owner, Observer {
            it?.let {
                if (it.deviceMac !== null && it.refType.equals(Constants.DEV_TYPE_RFID)) {
                    activity.showDialog("设备连接中，请稍后...")
                    myRFID.connect(it.deviceMac, 10000)
                } else {
                    activity.toast("设备型号错误！")
                }
            }
        })
    }

    /**
    *
    * 读卡，生成二维码，写卡http请求获取二维码
    * author coky
    * created 2022/4/1 15:55
    */
    abstract fun doUpdate(activity: BaseActivity<*, *>)


    fun connBtnStatusChange() {//连接按钮状态改变
        toConnLD.value = !toConnLD.value!!
    }

    fun showBatterInfo() {//电量展示
        myRFID.getBatteryInfo()?.let {
            vBinding.tvDeviceElectricity.text = "当前电量：${it.level}%"
        }
    }

    fun regRFID() = myRFID.register(mUhfCallback) //注册

    fun unRegRFID() = myRFID.unRegister(mUhfCallback)  //注销

    //    构造回调
    private fun getUhfCallback() = object : UhfCallback {
        override fun onGetBtInfo(p0: BluetoothDevice?) {}

        //实现具体功能 0：连接成功  -1：断开连接  -2：连接超时  1：usb插入 -3：usb拔出
        override fun onGetConnectStatus(status: Int) {
            connStatusLD.value = status
        }

        //实现具体功能 获取寻卡EPC号
        override fun onGetTagsId(epcs: MutableList<EPC>?) {
            if (isEnable && epcs != null) {
                data.clear()
                for (epc in epcs) {
                    var epcBean = EpcBean()
                    epcBean.name = "获取中..."
                    epcBean.id = epc.id
                    epcBean.count = epc.count
                    epcBean.rssi = epc.rssi
                    epcBean.len = epc.len
                    epcBean.isPC = epc.isPC
                    data.add(epcBean)
                }
            }
        }

        //实现具体功能 1:开始寻卡  0：停止寻卡 2:读取离线  3:停止离线  4:单次 5：开始连续筛选
        override fun onGetScanKeyMode(mode: Int) {
            scanModeLD.value = mode
        }

        override fun onDecodeComplete(p0: DecodeInfo?) {}

    }


    //    -----------------view-------------------------------
    private fun viewConned(activity: BaseActivity<*, *>) {//连接成功
        vBinding.sbConn.let {
            it.setLeftText("${RFIDTool.deviceXH}连接成功")
            it.setRightText("断开连接")
            it.setLeftTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.green
                )
            )
        }
    
        viewModelScope.launch {
            delay(2000L)
            showBatterInfo()
        }
    }

    private fun viewDisConn(activity: BaseActivity<*, *>) {//连接断开
        vBinding.sbConn.let {
            it.setLeftText("${RFIDTool.deviceXH}连接断开")
            it.setRightText("扫码连接")
            it.setLeftTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.red
                )
            )
        }
    }

    private fun viewTimeOut(activity: BaseActivity<*, *>) {//连接超时
        vBinding.sbConn.let {
            it.setLeftText("${RFIDTool.deviceXH}连接超时")
            it.setRightText("扫码连接")
            it.setLeftTextColor(
                ContextCompat.getColor(
                    activity,
                    R.color.red
                )
            )
        }
    }

//    private fun viewFindedTag() {//寻到标签，这个方法需要在子类去实现，不同的界面，view不一样，后期可以合并到doupdate
//        vBinding.tvTips.visibility = View.GONE
//        vBinding.rfidItem.tvBqnr.text = getTagContent()
//        vBinding.rfidItem.tvXhqd.text = getSignPower()
//        (activity as RFIDAct<*>).loadView()
//    }

    fun getTagContent() = "标签内容：${RFIDTool.hexStr2str(currentRssiMax?.getId()!!)}"//标签内容
    fun getSignPower() =  "信号强度：${currentRssiMax?.rssi}"//信号强度





    class EpcBean : EPC() {
        var name: String = ""
    }
}